<template>
  <!-- 会员中心 -->
  <div class="community">
    <!--<magic-header titleName="社区" :hideReturn="true"></magic-header>-->
    

    <!--start tabs-->
    <tabs :tabData="tabData" class="tab-title" @removeRed="removeRed" @changeTab="init">
      <!-- 新动态提醒: 评论,点赞等操作 -->
      <!-- <div class="newmsg-btn"> -->
      <div class="newmsg-btn" v-if="newMessageList && newMessageList.length > 0">
        <button v-tap="{methods: goNewMessage, name: nickName}">
          您有{{newMessageList.length}}条未读消息
        </button>
      </div>

      <!-- 车友会动态 -->
      <div class="" slot="tab0">
        <loadmore :getMore="loadMore">
        	
        	<!--start swiper 图片轮播 -->
    <swipe class="my-swipe" v-if="banner.length > 0">
      <swipe-item v-for="(item,index) in banner" :key="index" class="swiper">
        <img class="swipe-img" :src="item.image" v-tap="{methods:go,path:item.path}" />
      </swipe-item>
    </swipe>
    <div style="margin-top:20px;"></div>
    <!--<div v-else class="defaultImg">
      <img :src="carFriend" />
    </div>-->
    <!--end swiper -->

    <!--start 带颜色选择按钮 -->
    <div class="select-btn">
      <div class="carfriend-meet" v-tap="{methods:goMeet}">
        车友会
        <div v-if="newFleet" class="red-msg"></div>
      </div>
      <div class="city-active" v-tap="{methods:goActive}">
        同城活动
        <div v-if="newActive" class="red-msg"></div>
      </div>
      <div class="hot-discuss" v-tap="{methods:goDiscussion}">
        热门讨论
        <div v-if="newDiscuss" class="red-msg"></div>
      </div>
      <div class="carfriend" v-tap="{methods:goNative}">
        车友
        <div v-if="newCarfri" class="red-msg"></div>
      </div>
    </div>
    <!--end 带颜色选择按钮 -->
    
    
    
          <div v-if="carMeetDynamic.length>0" v-for="(item, index) in carMeetDynamic" :key="index">
            <dynamic :itemData="item"></dynamic>
          </div>
        </loadmore>
      </div>

      <!-- 车友动态 -->
      <div class="" slot="tab1">
        <!-- 发状态按钮 -->
        <div class="btn-addDynamic">
          <i class="iconfont" v-tap="{methods: pubDynamic}">&#xe61f;</i>
        </div>
        <loadmore :getMore="loadMoreCarFriend">
        	
        	<!--start swiper 图片轮播 -->
    <swipe class="my-swipe" v-if="banner.length > 0">
      <swipe-item v-for="(item,index) in banner" :key="index" class="swiper">
        <img class="swipe-img" :src="item.image" v-tap="{methods:go,path:item.path}" />
      </swipe-item>
    </swipe>
    <div style="margin-top:20px;"></div>
    <!--<div v-else class="defaultImg">
      <img :src="carFriend" />
    </div>-->
    <!--end swiper -->

    <!--start 带颜色选择按钮 -->
    <div class="select-btn">
      <div class="carfriend-meet" v-tap="{methods:goMeet}">
        车友会
        <div v-if="newFleet" class="red-msg"></div>
      </div>
      <div class="city-active" v-tap="{methods:goActive}">
        同城活动
        <div v-if="newActive" class="red-msg"></div>
      </div>
      <div class="hot-discuss" v-tap="{methods:goDiscussion}">
        热门讨论
        <div v-if="newDiscuss" class="red-msg"></div>
      </div>
      <div class="carfriend" v-tap="{methods:goNative}">
        车友
        <div v-if="newCarfri" class="red-msg"></div>
      </div>
    </div>
    <!--end 带颜色选择按钮 -->
    
          <div v-for="(item, index) in carFriendDynamic" :key="index">
            <dynamic :itemData="item" @removeSuccess="removeDynamic(index,carFriendDynamic)"></dynamic>
          </div>
        </loadmore>
      </div>
    </tabs>
  </div>
</template>

<script>
// obj
import Vue from "vue";
// components
import magicHeader from "components/magicHeader";
import dynamic from "components/dynamic/dynamic";
import tabs from "components/tab/tabs";
import loadmore from "components/scroll/scroll";
import carFriend from "assets/carFriend.png";
import defaultAvatar from "assets/default_user_icon.png";
// service
import carFriendService from "services/carFriend/carFriend";
import QueryAdPositionService from "services/carFriend/QueryAdPosition";
import QueryUserInfoService from "services/carFriend/QueryUserInfo";
import QueryNewEventAlarmService from "services/carFriend/QueryNewEventAlarm";
import QueryRidersSpaceService from "services/carFriend/QueryRidersSpace";
import QuerySpaceMessageService from "services/carFriend/QuerySpaceMessage";

let befTime = null;
let aftTime = null;
// 0-广告 1-用户信息 2-新消息 3-车友会动态列表 4-车友动态列表 5-查询新动态
const SERVICE_LIST = carFriendService.SERVICE_LIST;

export default {
  name: "community",
  components: {
    magicHeader,
    tabs,
    dynamic,
    loadmore
  },
  data() {
    return {
      banner: [], //轮播数据
      swiperDefault: [],
      carFriendDynamic: [], //车友会动态
      carMeetDynamic: [], //车友会动态
      tabData: [
        {
          title: "车友会动态",
          redMsg: false
        },
        {
          title: "车友动态",
          redMsg: false
        }
      ], //设置tab切换
      //	      redMsg:[true,true,true,true],
      newCarfri: "",
      newFleet: "",
      newActive: "",
      newDiscuss: "",
      newFleetDyn: "",
      newFriDyn: "",
      //        newMessage: '',
      replyDate: "10-17",
      carFriend: carFriend,
      defaultImg: defaultAvatar,
      refresh: false,
      requeryCount: 5,
      query: {
        index: 5,
        count: 5
      },
      requeryRidersSpaceCount: 5,
      queryRidersSpace: {
        index: 5,
        count: 5
      },
      nickName: "",
      lastTime: "",
      newMessageList: []
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.refresh = true;
      // 如果页面是从发动态操作返回的, 则滚动页面至顶端, 展示最新动态
      if (from.name == "carFri_pubDynamic") {
        setTimeout(() => window.scrollTo(0, {}), 0);
      }
      // 原生调用此方法，来控制车友小红点的显示
        		        Vue.prototype.$.register('data_sendNewMessage', vm)
    });
  },
  watch: {
    refresh(newV, oldV) {
      if (newV === true) {
        this.init();
      }
    }
  },
  methods: {
    init() {
      this.refresh = false;
      let vm = this;

      // 0-广告 1-用户信息 2-新消息 3-车友会动态列表 4-车友动态列表 5-查询新动态
      let servicePromiseList = [
        getServicePromise(vm, SERVICE_LIST[0].service, SERVICE_LIST[0].req)(),
        getServicePromise(vm, SERVICE_LIST[1].service, SERVICE_LIST[1].req)(),
        getServicePromise(vm, SERVICE_LIST[2].service, SERVICE_LIST[2].req)(),
        getServicePromise(vm, SERVICE_LIST[3].service, Object.assign({}, SERVICE_LIST[3].req, {count: this.requeryCount+''}))(),
        getServicePromise(vm, SERVICE_LIST[4].service, Object.assign({}, SERVICE_LIST[4].req, {count: this.requeryRidersSpaceCount+''}))(),
        getServicePromise(vm, SERVICE_LIST[5].service, Object.assign({}, SERVICE_LIST[5].req, { lastTime: window.localStorage.getItem("NewLastTime") }))()
      ];

      Promise.all(servicePromiseList).then(res => {
        console.log(res);
        // nickName
        this.nickName = res[1].userNickname;

        //swiper数据
        this.banner = res[0].ads;
        this.banner.forEach((item, index) => {
          item.image = this.addPath(item.image);
        });

        //红点显示
        if (res[2].resultCode === "100") {
          if (!window.localStorage.getItem("timeMap")) {
            window.localStorage.setItem(
              "timeMap",
              JSON.stringify(res[2].timeStampMap)
            );
          }
          befTime = JSON.parse(window.localStorage.getItem("timeMap"));
          aftTime = res[2].timeStampMap;
          this.newFleet = aftTime[6] !== befTime[6];
          this.newActive = aftTime[7] !== befTime[7];
          this.newDiscuss = aftTime[8] !== befTime[8];
          this.tabData[0].redMsg = aftTime[9] !== befTime[9];
          this.tabData[1].redMsg = aftTime[10] !== befTime[10];
        }

        //车友会动态
        let returnCarMeet = res[3].spaces;
        returnCarMeet.forEach((item, index) => {
          this.carMeetDynamic[index] = getDynamicItem(item, {
            avatar: item.fleet.head
              ? this.addPath(item.fleet.head)
              : this.defaultImg,
            name: item.fleet.name
          });
        });

        //车友动态
        let returnCarFriend = res[4].spaces;
        returnCarFriend.forEach((item, index) => {
          this.carFriendDynamic[index] = getDynamicItem(item, {
            avatar: item.member.head
              ? this.addPath(item.member.head)
              : this.defaultImg,
            name: item.member.nickname
          });
        });

        // 新动态
        // 1. NewLastTime中的数据只有每次去查看了未读消息才更新
        // 2. lastTime永远保存最新数据
        if (!window.localStorage.getItem("NewLastTime")) {
          window.localStorage.setItem("NewLastTime", res[5].lastestTime);
        }
        this.lastTime = res[5].lastestTime;
        this.newMessageList = res[5].spaceMessages;
      });
    },
    //swiper进入活动页
    go(params) {
      var arr = params.path.split("#");
      if (this.banner.length > 0) {
        this.$.go({
          name: "router_crossWebView",
          query: {
            project: "ec",
            routeAndParams: "#" + arr[1]
          }
        });
      }
    },
    //进入车友会
    goMeet() {
      this.$router.push({
        name: "carfri_meetLists"
      });
      if (this.newFleet === true) {
        this.newFleet = false;
        befTime[6] = aftTime[6];
        window.localStorage.setItem("timeMap", JSON.stringify(befTime));
      }
    },
    // 同城活动
    goActive() {
      this.$router.push({
        name: "city_active"
      });
      if (this.newActive === true) {
        this.newActive = false;
        befTime[7] = aftTime[7];
        window.localStorage.setItem("timeMap", JSON.stringify(befTime));
      }
    },
    // 热门讨论
    goDiscussion() {
      this.$router.push({
        name: "hot_discussion"
      });
      if (this.newDiscuss === true) {
        this.newDiscuss = false;
        befTime[8] = aftTime[8];
        window.localStorage.setItem("timeMap", JSON.stringify(befTime));
      }
    },
    // 进入原生车友页面
    goNative() {
      this.$.push("route_carFriends",{},res=>{});
    },
    removeRed(count) {
      befTime[9 + count] = aftTime[9 + count];
      window.localStorage.setItem("timeMap", JSON.stringify(befTime));
    },
    loadMore() {
      QueryRidersSpaceService.bind(this)(
        {
          index: this.query.index+'',
          count: this.query.count+'',
          type: "1"
        },
        res => {
          this.query.index += this.query.count;
          this.requeryCount += this.query.count;
          //车友会动态
          let returnCarMeet = res.spaces;
          returnCarMeet.forEach((item, index) => {
            this.carMeetDynamic.push(
              getDynamicItem(item, {
                avatar: item.fleet.head
                  ? this.addPath(item.fleet.head)
                  : this.defaultImg,
                name: item.fleet.name
              })
            );
          });

          console.log(this.carMeetDynamic);
        }
      );
    },
    loadMoreCarFriend() {
      QueryRidersSpaceService.bind(this)(
        {
          index: this.queryRidersSpace.index+'',
          count: this.queryRidersSpace.count+'',
          type: "0"
        },
        res => {
          this.queryRidersSpace.index += this.queryRidersSpace.count;
          this.requeryRidersSpaceCount += this.queryRidersSpace.count;
          //车友会动态
          let returnCarFriend = res.spaces;
          returnCarFriend.forEach((item, index) => {
            this.carFriendDynamic.push(
              getDynamicItem(item, {
                avatar: item.member.head
                  ? this.addPath(item.member.head)
                  : this.defaultImg,
                name: item.member.nickname
              })
            );
          });
        }
      );
    },
    // 发布动态
    pubDynamic() {
      this.$router.push({
        name: "carFri_pubDynamic"
      });
    },
    // 删除动态
    removeDynamic(index, list) {
      list.splice(index, 1);
    },
    // 查看新动态
    goNewMessage(params) {
      this.newMessageList = []
      this.$router.push({
        name: "new_message",
        params: {
          lastMessTime: window.localStorage.getItem("NewLastTime"),
          usernickName: params.name
        }
      });
      window.localStorage.setItem("NewLastTime", this.lastTime);
    }
  }
};

/**
 * 动态数据处理
 */
function getDynamicItem(item, cusItem) {
  return Object.assign({}, cusItem, {
    id: item.id,
    userId: item.member.id,
    publishDate: item.publishDate,
    content: item.content,
    share: item.share,
    audios: item.audios,
    images: item.images,
    topics: item.topics,
    videos: item.videos,
    commentCount: item.commentCount,
    supportCount: item.supportCount,
    comments: item.comments,
    isSupport: item.isSupport,
    title:item.title
  });
}

/**
 * 获取service promise对象
 */
function getServicePromise(vm, service, req) {
  return () => {
    return new Promise((resolve, reject) => {
      service.bind(vm)(req, res => {
        resolve(res);
      });
    });
  };
}
</script>

<style lang="scss" scoped>
.my-swipe {
  height: 180px;
  margin-bottom: 2em;
}

.swiper {
  height: 180px;
}

.swipe-img,
.defaultImg {
  width: 100%;
  margin-bottom: 1em;
}

.defaultImg img {
  width: 100%;
}

.select-btn {
  padding: 0 10px 0 10px;
  height: 50px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 1em;
}

.carfriend-meet,
.city-active,
.hot-discuss,
.carfriend {
  width: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  border-radius: 5px;
}

.carfriend-meet {
  position: relative;
  background: #f02b2b;
}

.city-active {
  position: relative;
  background: #548cd1;
}

.hot-discuss {
  position: relative;
  background: #f98700;
}

.carfriend {
  position: relative;
  background: #548cd1;
}

.red-msg {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(100%, -100%);
  width: 6px;
  height: 6px;
  border-radius: 3px;
  background: red;
}

.tab-title {
  position: relative;
}

.top .top .left img {
  border-radius: 0;
}

.btn-addDynamic {
  position: fixed;
  bottom: 5vh;
  right: 20px;
  z-index: 100;
  text-align: center;
  i {
    width: 40px;
    height: 40px;
    background: #f98700;
    border-radius: 50%;
    color: #fff;
    font-size: large;
    padding-left: 3px;
  }
}
.newmsg-btn {
  text-align: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
  button {
    padding: 8px 20px;
    border-radius: 20px;
    box-shadow: none;
    border: 1px solid #f98700;
    background: #f98700;
    color: #fff;
  }
}
</style>
<style lang="scss">
/*start 文章*/

.article-top {
  display: flex;
  .article-left {
    padding: 4px;
    img {
      width: 40px;
      height: 40px;
      flex: 1 1 0;
    }
  }
  .article-right {
    flex: 4 1 0;
    display: flex;
    flex-flow: column;
    justify-content: center;
    padding: 4px;
  }
}

/*end 文章*/
</style>
